package org.example.core;

import javax.swing.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Controller {
    boolean flag = false;
    private static String fileSavePath = "C:\\";
    private static final String fileSavePath1 = "values-";

    static final Map<String, String> LANGUAGE_MAP = new HashMap();

    private static final List<String> datalist = new ArrayList<>();
    private static String stringName = "";

    public void execute() {
        init();
//        String property = System.getProperty("user.dir");
//        System.out.println(property);
//        if (!property.isEmpty()){
//            fileSavePath = property+"\\trans\\";
//        }else {
//            fileSavePath = fileSavePath+"\\trans\\";
//        }
        listenStart();

    }

    public void save2File(String result, String fileSuffix) {

        StringBuilder sb1 = new StringBuilder(fileSavePath);
        sb1.append("\\");
        sb1.append(fileSavePath1);
        sb1.append(fileSuffix);
        sb1.append("\\string.xml");
//        往文件里面写内容
        try {
            File file = new File(sb1.toString());
            boolean exists = file.exists();
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                //                不能创建目录，不能乱改源码
                return;
//                parentFile.mkdirs();
            }
            if (!exists) {
//                不能创建文件，不能乱改源码
//                file.createNewFile();
                return;
            }
            StringBuilder sb = new StringBuilder();
            sb.append("<string name=\"" + stringName + "\">\"");
            String replace = result.replace("\n", "").replace("\r", "");
            sb.append(replace);
            sb.append("\"</string>\n</resources>");
            System.out.println(sb.toString());
            RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
            //获取文件长度
            long length = accessFile.length();
            //设置文件指针移动到文件末尾 </resources>之前
            accessFile.seek(length-12);
            accessFile.write(sb.toString().getBytes(StandardCharsets.UTF_8));
            accessFile.close();
//            StringBuilder sb =
//                    new StringBuilder("<?xml version=\"1.0\"?> \n <resources xmlns:android=\"http://schemas.android.com/apk/res/android\" " +
//                            "xmlns:xliff=\"urn:oasis:names:tc:xliff:document:1.2\">\n");
//            sb.append("<string name=\"" + stringName + "\">\"");
//            String replace = result.replace("\n", "").replace("\r", "");
//            sb.append(replace);
//            sb.append("\"</string>\n</resources>");
//            FileWriter fileWriter = new FileWriter(file,true);
//            fileWriter.write(sb.toString());
//            fileWriter.flush();
//            fileWriter.close();
//            PrintWriter printWriter = new PrintWriter(file);
//            printWriter.write(sb.toString());
//            printWriter.flush();
//            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    private void readResources() {
//        StringBuilder stringBuilder = new StringBuilder(fileSavePath);
//        StringBuilder content = new StringBuilder();
//        stringBuilder.append("values\\string.xml");
//        File file = new File(stringBuilder.toString());
//        if (!file.exists()) {
//            throw new RuntimeException("需要翻译的资源不存在!");
//        } else {
//            try {
//                BufferedReader bs = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
//                String s = "";
//                while ((s = bs.readLine()) != null) {
//                    content.append(s);
//                }
//                bs.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            System.out.println(content);
//            datalist.add(content.substring(content.indexOf("<string name=\"") + 14, content.lastIndexOf("\">")));
//            datalist.add(content.substring(content.indexOf("\">\"") + 3, content.lastIndexOf("\"<")));
//        }
//    }


    /**
     * 初始化语言类
     */
    private void init() {
        LANGUAGE_MAP.put("af", "Afrikaans");
        LANGUAGE_MAP.put("sq", "Albanian");
        LANGUAGE_MAP.put("am", "Amharic");
        LANGUAGE_MAP.put("ar", "Arabic");
        LANGUAGE_MAP.put("hy", "Armenian");
        LANGUAGE_MAP.put("az", "Azerbaijani");
        LANGUAGE_MAP.put("eu", "Basque");
        LANGUAGE_MAP.put("be", "Belarusian");
        LANGUAGE_MAP.put("bn", "Bengali");
        LANGUAGE_MAP.put("bs", "Bosnian");
        LANGUAGE_MAP.put("bg", "Bulgarian");
        LANGUAGE_MAP.put("ca", "Catalan");
        LANGUAGE_MAP.put("ceb", "Cebuano");
        LANGUAGE_MAP.put("ny", "Chichewa");
        LANGUAGE_MAP.put("zh-CN", "Chinese Simplified");
        LANGUAGE_MAP.put("zh-TW", "Chinese Traditional");
        LANGUAGE_MAP.put("co", "Corsican");
        LANGUAGE_MAP.put("hr", "Croatian");
        LANGUAGE_MAP.put("cs", "Czech");
        LANGUAGE_MAP.put("da", "Danish");
        LANGUAGE_MAP.put("nl", "Dutch");
        LANGUAGE_MAP.put("en", "English");
        LANGUAGE_MAP.put("eo", "Esperanto");
        LANGUAGE_MAP.put("et", "Estonian");
        LANGUAGE_MAP.put("tl", "Filipino");
        LANGUAGE_MAP.put("fi", "Finnish");
        LANGUAGE_MAP.put("fr", "French");
        LANGUAGE_MAP.put("fy", "Frisian");
        LANGUAGE_MAP.put("gl", "Galician");
        LANGUAGE_MAP.put("ka", "Georgian");
        LANGUAGE_MAP.put("de", "German");
        LANGUAGE_MAP.put("el", "Greek");
        LANGUAGE_MAP.put("gu", "Gujarati");
        LANGUAGE_MAP.put("ht", "Haitian Creole");
        LANGUAGE_MAP.put("ha", "Hausa");
        LANGUAGE_MAP.put("haw", "Hawaiian");
        LANGUAGE_MAP.put("iw", "Hebrew");
        LANGUAGE_MAP.put("hi", "Hindi");
        LANGUAGE_MAP.put("hmn", "Hmong");
        LANGUAGE_MAP.put("hu", "Hungarian");
        LANGUAGE_MAP.put("is", "Icelandic");
        LANGUAGE_MAP.put("ig", "Igbo");
        LANGUAGE_MAP.put("id", "Indonesian");
        LANGUAGE_MAP.put("ga", "Irish");
        LANGUAGE_MAP.put("it", "Italian");
        LANGUAGE_MAP.put("ja", "Japanese");
        LANGUAGE_MAP.put("jw", "Javanese");
        LANGUAGE_MAP.put("kn", "Kannada");
        LANGUAGE_MAP.put("kk", "Kazakh");
        LANGUAGE_MAP.put("km", "Khmer");
        LANGUAGE_MAP.put("ko", "Korean");
        LANGUAGE_MAP.put("ku", "Kurdish (Kurmanji)");
        LANGUAGE_MAP.put("ky", "Kyrgyz");
        LANGUAGE_MAP.put("lo", "Lao");
        LANGUAGE_MAP.put("la", "Latin");
        LANGUAGE_MAP.put("lv", "Latvian");
        LANGUAGE_MAP.put("lt", "Lithuanian");
        LANGUAGE_MAP.put("lb", "Luxembourgish");
        LANGUAGE_MAP.put("mk", "Macedonian");
        LANGUAGE_MAP.put("mg", "Malagasy");
        LANGUAGE_MAP.put("ms", "Malay");
        LANGUAGE_MAP.put("ml", "Malayalam");
        LANGUAGE_MAP.put("mt", "Maltese");
        LANGUAGE_MAP.put("mi", "Maori");
        LANGUAGE_MAP.put("mr", "Marathi");
        LANGUAGE_MAP.put("mn", "Mongolian");
        LANGUAGE_MAP.put("my", "Myanmar (Burmese)");
        LANGUAGE_MAP.put("ne", "Nepali");
        LANGUAGE_MAP.put("no", "Norwegian");
        LANGUAGE_MAP.put("ps", "Pashto");
        LANGUAGE_MAP.put("fa", "Persian");
        LANGUAGE_MAP.put("pl", "Polish");
        LANGUAGE_MAP.put("pt", "Portuguese");
        LANGUAGE_MAP.put("pa", "Punjabi");
        LANGUAGE_MAP.put("ro", "Romanian");
        LANGUAGE_MAP.put("ru", "Russian");
        LANGUAGE_MAP.put("sm", "Samoan");
        LANGUAGE_MAP.put("gd", "Scots Gaelic");
        LANGUAGE_MAP.put("sr", "Serbian");
        LANGUAGE_MAP.put("st", "Sesotho");
        LANGUAGE_MAP.put("sn", "Shona");
        LANGUAGE_MAP.put("sd", "Sindhi");
        LANGUAGE_MAP.put("si", "Sinhala");
        LANGUAGE_MAP.put("sk", "Slovak");
        LANGUAGE_MAP.put("sl", "Slovenian");
        LANGUAGE_MAP.put("so", "Somali");
        LANGUAGE_MAP.put("es", "Spanish");
        LANGUAGE_MAP.put("su", "Sundanese");
        LANGUAGE_MAP.put("sw", "Swahili");
        LANGUAGE_MAP.put("sv", "Swedish");
        LANGUAGE_MAP.put("tg", "Tajik");
        LANGUAGE_MAP.put("ta", "Tamil");
        LANGUAGE_MAP.put("te", "Telugu");
        LANGUAGE_MAP.put("th", "Thai");
        LANGUAGE_MAP.put("tr", "Turkish");
        LANGUAGE_MAP.put("uk", "Ukrainian");
        LANGUAGE_MAP.put("ur", "Urdu");
        LANGUAGE_MAP.put("uz", "Uzbek");
        LANGUAGE_MAP.put("vi", "Vietnamese");
        LANGUAGE_MAP.put("cy", "Welsh");
        LANGUAGE_MAP.put("xh", "Xhosa");
        LANGUAGE_MAP.put("yi", "Yiddish");
        LANGUAGE_MAP.put("yo", "Yoruba");
        LANGUAGE_MAP.put("zu", "Zulu");
    }

    /**
     * 获取 语言代码
     * ISO 639-1 code
     *
     * @param desiredLang 语言
     * @return 如果返回null则标示不支持
     */
    public String getCode(String desiredLang) {
        if (null != LANGUAGE_MAP.get(desiredLang)) {
            return desiredLang;
        }
        String tmp = desiredLang.toLowerCase();
        for (Map.Entry<String, String> enter : LANGUAGE_MAP.entrySet()) {
            if (enter.getValue().equals(tmp)) {
                return enter.getKey();
            }
        }

        return null;
    }


    private void listenStart() {
        View view = new View();
        view.listenBtn();
        view.start.addActionListener(e -> {

            String text = view.savePathField.getText();
            String text1 = view.transKeyFiled.getText();
            String text2 = view.transTextField.getText();

            if (view.isEmpty(text) || view.isEmpty(text1) || view.isEmpty(text2)) {
                JOptionPane.showMessageDialog(
                        view,
                        "输入的信息不完整，请完善信息才能执行翻译哟！",
                        "消息",
                        JOptionPane.WARNING_MESSAGE
                );
            } else {
//                执行翻译
                if (!flag) {
                    flag = true;
                    view.start.setFocusPainted(false);
                    datalist.clear();
                    fileSavePath = text;
                    System.out.println("save path is===> " + text);
                    System.out.println("key is===> " + text1);
                    System.out.println("value is===> " + text2);
                    GT g = GT.getInstance();
                    stringName = text1;
                    try {
                        g.translateText(text2, "auto", "en");
                    } catch (Exception aa) {
                        aa.printStackTrace();
                    }
                }
            }

        });
    }

}
